package com.uzai.console.web.ks;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.doudian.open.api.buyin_doukePidCreate.BuyinDoukePidCreateRequest;
import com.doudian.open.api.buyin_doukePidCreate.BuyinDoukePidCreateResponse;
import com.doudian.open.api.buyin_doukePidCreate.param.BuyinDoukePidCreateParam;
import com.doudian.open.core.AccessToken;
import com.doudian.open.core.AccessTokenBuilder;
import com.doudian.open.core.GlobalConfig;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.RandomUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.entity.KsToken;
import com.uzai.console.service.ks.KsTokenCallBackService;
import com.uzai.console.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URLEncoder;

/**
 * @author lucher
 * @date 2019-06-17 11:39
 */
@Api(value = "快手回调函数",tags = "快手|快手联盟", hidden = true)
@ApiSort(10)
@RestController
public class KsTokenCallbackController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger(KsTokenCallbackController.class);

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private KsTokenCallBackService ksTokenCallBackService;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;

    /**
     * 回调获取授权
     * @param code
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "快手联盟刷新授权回调函数", hidden = true)
    @GetMapping("/ks/callback")
    public void callback(String code, String state) throws Exception {
        logger.info("code:{},state:{}",new Object[]{code, state});

        try{
            AccessToken accessToken = AccessTokenBuilder.build(code);
            String access_token = accessToken.getAccessToken();
            String refresh_token = accessToken.getRefreshToken();
            Long expireIn = Tools.getLong(accessToken.getExpireIn()); //有效时长（单位秒）
            String authority_id = accessToken.getAuthorityId();
            KsToken ksToken = new KsToken();
            int now = DateUtil.getNowTime();
            ksToken.setId(IdWorker.getId());
            ksToken.setMerId(Long.parseLong(state));
            ksToken.setName("快手随机账号_" + RandomUtil.getSmsCode(4));
            ksToken.setAppId(authority_id);
            ksToken.setAccessToken(access_token);
            ksToken.setRefreshToken(refresh_token);
            ksToken.setExptime(now + expireIn.intValue());
            ksToken.setType(1); //联盟类型：0 cookie模式，1 官方api模式
            ksToken.setCreateTime(now);
            ksToken.setUpdateTime(now);
            //调用token保存方法
            ksTokenCallBackService.add(ksToken);
            getResponse().sendRedirect(uzaiConsoleSysConfig.getTokenAuthReturnUrl() + "?state=1");
        }catch(Exception e){
            logger.error("callback err:{}",e);
            getResponse().sendRedirect(uzaiConsoleSysConfig.getTokenAuthReturnUrl() + "?state=0&msg="+ URLEncoder.encode(e.getMessage(),"UTF-8"));
        }
    }

    public static void main(String[] args) {

        //初始化快手配置
        GlobalConfig.initAppKey("7042184729914770975");
        GlobalConfig.initAppSecret("a6b7a1ce-aecd-4d71-a208-5b8e40d01cd5");

        BuyinDoukePidCreateRequest request = new BuyinDoukePidCreateRequest();
        BuyinDoukePidCreateParam param = request.getParam();
        param.setMediaType(1);
        param.setMediaName("uzai_3.0");
        //param.setMediaId(222L);
        param.setSiteName(RandomUtil.getSmsCode(6)); //随机6位字符
        AccessToken accessToken = AccessTokenBuilder.parse("27aaaaec-f1a0-4b85-a4a8-ab75731c23c9");
        BuyinDoukePidCreateResponse response = request.execute(accessToken);
        if(response != null && response.getData() != null){
            logger.info("--获取快手联盟PID-- data={}", response.getData().toString());
            String pid = response.getData().getPid();
            logger.info(pid);
        }
    }

}
